package pers.vic.test.attachment.controller;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import pers.vic.boot.base.model.BaseResponse;
import pers.vic.test.attachment.modle.FileModel;

/**
 * @description:
 * @author: Vic.xu
 * @date: 2019年12月28日 下午11:37:12
 */
@Controller
@RequestMapping("/mineFile")
public class MineFileController {

	@Value("${upload.path}")
	private String filPath;

	@GetMapping(value = { "", "/", "/home" })
	public String home(Model model) {
		List<FileModel> list = new ArrayList<FileModel>();
		new File(filPath).listFiles(new FileFilter() {

			@Override
			public boolean accept(File pathname) {
				String fileName = pathname.getName();
				long size = pathname.length();
				list.add(new FileModel(fileName, size));
				return false;
			}
		});
		model.addAttribute("list", list);
		return "mine-files/index";
	}

	/**
	 * 文件列表
	 */
	@GetMapping("/list")
	@ResponseBody
	public BaseResponse<?> list() {
		List<FileModel> list = new ArrayList<FileModel>();
		new File(filPath).listFiles(new FileFilter() {

			@Override
			public boolean accept(File pathname) {
				String fileName = pathname.getName();
				long size = pathname.length();
				list.add(new FileModel(fileName, size));
				return false;
			}
		});
		return BaseResponse.success(list);
	}

	/**
	 * 删除文件
	 */
	@GetMapping("/delete")
	public BaseResponse<?> delete(String fileName) {
		FileUtils.deleteQuietly(new File(filPath, fileName));
		return BaseResponse.success();
	}

	/**
	 * 上传
	 */
	@PostMapping("upload")
	@ResponseBody
	public BaseResponse<?> upload(MultipartFile file) {
		try {
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File(filPath, file.getOriginalFilename()));
		} catch (Exception e) {
			e.printStackTrace();
			return BaseResponse.error(e.getMessage());
		}
		return BaseResponse.success();
	}

}
